using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {
	
	public GameObject player;
    public GameObject manager;
	public float rightDisplacementThreshold = -4.0f;
	public float screenWidthToPan = 9.0f;
	public float panSpeedInFrames = 30.0f;
	private Vector3 targetCameraPosition;
	
	// Use this for initialization
	void Start () {
		// Start the target camera position where the camera defaults to
		// i.e. don't move.
		targetCameraPosition = gameObject.transform.position;
	}
	
	// Update is called once per frame
	void Update () {
        if (!player) return;
		// Calculate the diplacement between the user's position and the camera's position
		Vector2 displacement = Vector2.zero;
        Vector2 this2D = new Vector2(gameObject.transform.position.x, gameObject.transform.position.z);
        Vector2 player2D = new Vector2(player.transform.position.x, player.transform.position.z);
        displacement.x = this2D.x - player2D.x;
        displacement.y = this2D.y - player2D.y;
		
		// Check if the user has walked to the right edge of the screen
		if (displacement.x < rightDisplacementThreshold) {
			Vector3 cameraTranslation = new Vector3(screenWidthToPan, 0.0f, 0.0f);
			targetCameraPosition = gameObject.transform.position + cameraTranslation;
		}
		
		panToTargetCameraPosition();
	}
	
	// Pan the camera to the new target location
	void panToTargetCameraPosition() {
		if (this.transform.position != targetCameraPosition) {
			float panIncrement = 9.0f / panSpeedInFrames;
			
			if (Mathf.Abs(this.transform.position.x - targetCameraPosition.x) <= panIncrement) {
				// If we're close enough to the target position
				this.transform.position = targetCameraPosition;
                manager.GetComponent<GameManager>().AdvanceStage();
			} else {
				// Pan a bit
				Vector3 cameraTranslation = new Vector3(panIncrement, 0.0f, 0.0f);
				this.transform.position = this.transform.position + cameraTranslation;
			}
		}
	}
}
